<?php

namespace App\Http\Controllers\Activity;

use App\Http\Controllers\Controller;
use App\Http\Requests;
use App\Lib\WxWechat;
use Illuminate\Http\Request;
use DB;
use Ixudra\Curl\Facades\Curl;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Cache;

class MainController extends Controller
{
	private $WX_HOST = "https://emedia.sbedian.com";
	private $KEY = 'Ill0NMFSUlCfbX3J';
	private $CHANNEL_ID = 'ptPvoD9TFaTo3PysDCuOZjlwEBy6H96T';
	private $appid = 'wxb8f879f3ecc43dc5';
	
	public function activityView(Request $request){
		
		$sId = $request->input('sId');
		$adId = $request->input('adId');
		$info = $request->input('info', false);
		$code = $request->input('code', false);
		$referrer = $request->input('referrerCode');
		$custom = $request->input('custom');
		
		$WX_HOST = "https://emedia.sbedian.com";
		
//		if ($referrer){
//			// 添加分享数
//			DB::table('activity_definition')->where('adId', $adId)->increment('adShareNum');
//		}
		
		if (!$code){
			$host = $WX_HOST."/auth/wxHtmAuth";
			$thisUrl = urlencode(route('activityView'));
			$authUrl = $host."?redirect_uri={$thisUrl}&scope=snsapi_userinfo&custom=".$referrer.'_'.$adId.'_'.$sId."&appid=".$this->appid;
			return redirect($authUrl);
		}
		
//		if (!$info){
//			$host = $WX_HOST."/auth/wxHtmAuthorization";
//			$thisUrl = urlencode(route('activityView')."?sId=".$sId);
//			$authUrl = $host."?targetUrl={$thisUrl}&scope=snsapi_userinfo&custom=".$referrer.'_'.$adId."&appid=".$this->appid;
//			return redirect($authUrl);
//		}

//		$wxHtmlAuthorizeInfo = json_decode($info, true);
		$wxHtmlAuthorizeInfo = $this->getInfo($code);
		//print_r($wxHtmlAuthorizeInfo);exit;
		$paramArray = explode("_", $custom);
		$referrerId = $paramArray[0];
		$adId = $paramArray[1];
		$sId = $paramArray[2];
		
		if ($wxHtmlAuthorizeInfo == false){
			$thisUrl = route('activityView')."?sId=".$sId."&adId=".$adId."&referrerCode=".$referrerId;
			return redirect($thisUrl);
		}
		
		// 添加浏览数
	    DB::table('activity_definition')->where('adId', $adId)->increment('adViewNum');

		$muInfo = $this->registerOrSign($sId, $wxHtmlAuthorizeInfo, $referrerId, $adId);
		
		if ($referrerId){
			$shareResult = $this->addShareLog($sId, $adId, $muInfo['muCode'], $referrerId);
			if ($shareResult){
				// 添加分享人数
				DB::table('activity_definition')->where('adId', $adId)->increment('adShareNum');
			}
		}
		
//		print_r($muInfo);exit;
		$activityInfo = DB::table('activity_definition')->where('adId', $adId)->first();
		$applyList = DB::table('activity_apply')
						->select(['activity_apply.aaName', 'activity_apply.aaPhone', 'activity_apply.createTime', 'member_users.muHeadUrl'])
						->leftJoin('member_users', 'activity_apply.uId', '=', 'member_users.muCode') 
						->where('activity_apply.acId', $sId)
						->where('activity_apply.adId', $activityInfo->adId)
						->where('aaStats', 1)
						->orderBy('activity_apply.aaId', 'ASC')
						->get();
						
		$shareList = DB::table('activity_apply')
						->leftJoin('member_users', 'activity_apply.uId', '=', 'member_users.muCode') 
						->where('activity_apply.acId', $sId)
						->where('activity_apply.adId', $activityInfo->adId)
						->where('activity_apply.aaShareMoney', '>', 0)
						->where('aaStats', 1)
						->orderBy('activity_apply.aaShareMoney', 'DESC')
						->get();
		
		$sInfo = DB::table('store')->where('sId', $sId)->first();
		
		$timeInfo = $this->common->timediff(strtotime($activityInfo->adApplyBeginTime), strtotime($activityInfo->adApplyEndTime));
//		print_r($muInfo);exit;
		$myApplyInfo = DB::table('activity_apply')
						->leftJoin('member_users', 'activity_apply.uId', '=', 'member_users.muCode') 
						->where('activity_apply.acId', $sId)
						->where('activity_apply.adId', $activityInfo->adId)
						->where('uId', $muInfo['muCode'])
						->first();
			
		$myRank = 0;		
		if ($myApplyInfo && $myApplyInfo->aaShareMoney > 0){
			$myRank = DB::table('activity_apply')
						->where('activity_apply.acId', $sId)
						->where('activity_apply.adId', $activityInfo->adId)
						->where('activity_apply.aaShareMoney', '>' ,$myApplyInfo->aaShareMoney)
						->count();
			$myRank = $myRank + 1;
		}
		
		$thisUrl = route('activityView')."?sId=".$sId."&adId=".$adId;
		$shareUrl = $thisUrl."&referrerCode=".$muInfo['muCode'];
		
		$options = array('token' => 'sdxvTQLlNhiEk9d8PsYzUpzToqUWMEoo', //填写你设定的key
	        'encodingaeskey' => 'MTWJzvuaGkhi6ipNfyA0yfVPcneqctl2e24nvpbGKra', //填写加密用的EncodingAESKey，如接口为明文模式可忽略
	        'appid' => 'wx8ab9feb80f4bc7e4', //填写高级调用功能的app id
	        'appsecret' => '488dd10ac2ba499ba30559b8b16c4f5d' //填写高级调用功能的密钥
        );
//      print_r($this->get_current_url());exit;
		$WxWechat = new WxWechat($options);
		$wxJsSign = $WxWechat->getJsSign($this->get_current_url());
		
		return view("activity/main", array(
								'muInfo' => $muInfo, 
								'applyList' => $applyList, 
								'myApplyInfo' => $myApplyInfo,
								'sInfo' => $sInfo, 
								'activityInfo' => $activityInfo,
								'timeInfo' => $timeInfo,
								'myRank' => $myRank,
								'shareList' => $shareList,
								'shareUrl' => $shareUrl,
								'wxJsSign' => $wxJsSign,
								'payHost' => $WX_HOST,
								'referrerId' => $custom       // 就是传这些参数调用getWxPayUrl
							)
					);
	}
	
	
	//php获取当前访问的完整url地址
	public function get_current_url(){
	    $current_url='http://';
	    if(isset($_SERVER['HTTPS'])&&$_SERVER['HTTPS']=='on'){
	        $current_url='https://';
	    }
	    if($_SERVER['SERVER_PORT']!='80'){
	        $current_url.=$_SERVER['SERVER_NAME'].':'.$_SERVER['SERVER_PORT'].$_SERVER['REQUEST_URI'];
	    }else{
	        $current_url.=$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
	    }
	    return $current_url;
	}

	
	public function registerOrSign($sId, $wxHtmlAuthorizeInfo, $muReferrerId=false, $adId=0){
//		{   
//		    "openid":" OPENID",
//		    " nickname": NICKNAME,
//		    "sex":"1",
//		    "province":"PROVINCE"
//		    "city":"CITY",
//		    "country":"COUNTRY",
//		    "headimgurl":       "http://thirdwx.qlogo.cn/mmopen/g3MonUZtNHkdmzicIlibx6iaFqAc56vxLSUfpb6n5WKSYVY0ChQKkiaJSgQ1dZuTOgvLLrhJbERQQ4eMsv84eavHiaiceqxibJxCfHe/46",
//		    "privilege":[ "PRIVILEGE1" "PRIVILEGE2"     ],
//		    "unionid": "o6_bmasdasdsad6_2sgVt7hMZOPfL"
//		}
		
		$muInfo = DB::table('member_users')->where('mcId', $sId)->where('openid', $wxHtmlAuthorizeInfo['openid'])->first();
		if (empty($muInfo)){
			$muCode = $this->create_guid();
			$alId = DB::table('agency_level')
						->selectRaw('MIN(alLevel) AS alLevel, alId')
						->where('acId', $sId)
						->value('alId');
			
			$muInfo = array();
			$muInfo['mcId'] = $sId;
			$muInfo['muCode'] = $muCode;
			$muInfo['muNickName'] = $wxHtmlAuthorizeInfo['nickname'];
			
			if ($wxHtmlAuthorizeInfo['sex'] == 1){
				$sex = 1;
			} else if ($wxHtmlAuthorizeInfo['sex'] == 2){
				$sex = 0;
			} else {
				$sex = 0;
			}
			$muInfo['muSex'] = $sex;
			$muInfo['muHeadUrl'] = $wxHtmlAuthorizeInfo['headimgurl'];
			$muInfo['openid'] = $wxHtmlAuthorizeInfo['openid'];
			$muInfo['alId'] = $alId;
			$muInfo['muSource'] = 'activity_'.$adId;
			$muId = DB::table('member_users')->insertGetId($muInfo);
			$muInfo['muId'] = $muId;
			if ($muReferrerId){
				$muInfo['muReferrerId'] = $muReferrerId;
			}
		}
		$muInfo = json_decode(json_encode($muInfo), true);
		return $muInfo;
	}
	
	private function create_guid() {
		$charid = md5(uniqid(mt_rand(), true));
		$hyphen = chr(45);// "-"
		$uuid = substr($charid, 0, 8)
				.substr($charid, 8, 4)
				.substr($charid,12, 4)
				.substr($charid,16, 4)
				.substr($charid,20,12);
		return $uuid;
	}
	
	public function getWxPayJson(Request $request){

		$adId = $request->adId;
		$muReferrerId = $request->referrerId;
		$username = $request->name;
		$userMobile = $request->mobile;
		$openid = $request->openid;

		$activityInfo = DB::table('activity_definition')->where('adId', $adId)->first();
		$muInfo = DB::table('member_users')->where('mcId', $activityInfo->acId)->where('openid', $openid)->first();

		$aaOrderId = $this->applyActivity($adId, $username, $userMobile, $muReferrerId, $muInfo->muCode);
		if ($aaOrderId === false){
			return $this->returnMsg(0, '该手机号已报名，不能重复报名');
		}
		
		// 更新姓名和手机号
		DB::table('member_users')
			->where('mcId', $activityInfo->acId)
			->where('openid', $openid)->update([
				'muNickName' => $username,
				'muRealName' => $username,
				'muMobile' => $userMobile
			]);
		
		$desc = $activityInfo->adTitle;
		$ip = $request->getClientIp();
		$key = $this->KEY;
		
		$payData = array();
		$payData['pcKey'] = $key;
		$payData['clientIp'] = $ip;
		$payData['pay'] = $activityInfo->adCurrentPrice;
		$payData['desc'] = $activityInfo->adTitle;
		$payData['openid'] = $openid;
		$payData['customOrderId'] = $aaOrderId;
		
		$payUrl = $this->WX_HOST.'/api/pay/unifyOrder';
		
		$payInfo = Curl::to($payUrl)->withData($payData)->post();
		
		return $payInfo;
	}
	
	public function getWxPayUrl(Request $request){

		$adId = $request->adId;
		$muReferrerId = $request->referrerId;
		$username = $request->name;
		$userMobile = $request->mobile;
		$openid = $request->openid;

		$activityInfo = DB::table('activity_definition')->where('adId', $adId)->first();
		$muInfo = DB::table('member_users')->where('mcId', $activityInfo->acId)->where('openid', $openid)->first();

		$aaOrderId = $this->applyActivity($adId, $username, $userMobile, $muReferrerId, $muInfo->muCode);
		if ($aaOrderId === false){
			return $this->returnMsg(0, '已经报名，不能重复报名');
		}
		
		$activityInfo = DB::table('activity_definition')->where('adId', $adId)->first();
		$desc = $activityInfo->adTitle;
		$ip = $request->getClientIp();
		$key = $this->KEY;
		
		$payData = array();
		$payData['pcKey'] = $key;
		$payData['clientIp'] = $ip;
		$payData['pay'] = $activityInfo->adCurrentPrice;
		$payData['desc'] = $activityInfo->adTitle;
		$payData['openid'] = $openid;
		$payData['customOrderId'] = $aaOrderId;
//		$payData['businessName'] = '';
		$payData['customInfo'] = $muReferrerId;
		
		$paramArray = explode("_", $muReferrerId);
		$referrerId = $paramArray[0];
		$adId = $paramArray[1];
		$sId = $paramArray[2];
		
		$payData['successUrl'] = route('activityView')."?adId=".$adId."&sId=".$activityInfo->acId."&referrerCode=".$referrerId;
		$payData['failureUrl'] = route('activityView')."?adId=".$adId."&sId=".$activityInfo->acId."&referrerCode=".$referrerId;
		
		$payUrl = $this->WX_HOST.'/api/pay/payPage?';
		$params = "";
		foreach($payData as $key => $value){
			$params = $params.'&'.$key.'='.urlencode($value);
		}
		$payUrl = $payUrl.substr($params, 1);
		//$payInfo = Curl::to($payUrl)->withData($payData)->post();
		return $this->returnMsg(1, 'OK', $payUrl);
	}
	
	private function applyActivity($adId, $aaName, $aaPhone, $aaReferrerId, $uId){
		
		$applyInfo = DB::table('activity_apply')
						->where('adId', $adId)
						->where('uId', $uId)
						->where('aaStats', 1)
						->first();
		if (!empty($applyInfo)){
			return false;
		}
		
		$now = date('YmdHis', time());
		
		$aaOrderId = $now.$adId.rand(1, 10000);
		$aaCode = $this->create_guid();
		
		$activityInfo = DB::table('activity_definition')->where('adId', $adId)->first();
		$aaPrice = $activityInfo->adCurrentPrice;
		$aaIsRefund = $activityInfo->adIsCanRefund;
		$aaCanUseNum = $activityInfo->adCanUseNum;
		$acId = $activityInfo->acId;
		
		DB::table('activity_apply')->insert([
			"uId" => $uId,
			"acId" => $acId,
			"aaOrderId" => $aaOrderId,
			"aaCode" => $aaCode,
			"aaPrice" => $aaPrice,
			"aaIsRefund" => $aaIsRefund,
			"aaCanUseNum" => $aaCanUseNum,
			"adId" => $adId,
			"aaName" => $aaName,
			"aaPhone" => $aaPhone,
			"aaReferrerId" => $aaReferrerId,
		]);
		
		return $aaOrderId;
	}

	public function payCallback(Request $request){
//		{
//			"appid": "wxfe2b6f9495c16bc0",
//			"bank_type": "CFT",
//			"cash_fee": "1",
//			"fee_type": "CNY",
//			"is_subscribe": "N",
//			"mch_id": "1233687902",
//			"nonce_str": "Ukrmvh7jXOEQL4PR",
//			"openid": "opSf40A-pyfBG7-AgsrcqHCxAH-U",
//			"out_trade_no": "4A99C505F2914A1A950A494C497D9D14",
//			"result_code": "SUCCESS",
//			"return_code": "SUCCESS",
//			"sign": "20EECE4A238F55DD977C90849FF1F8B3",
//			"time_end": "20180903110023",
//			"total_fee": "1",
//			"trade_type": "JSAPI",
//			"transaction_id": "4200000186201809039798978083",
//			"customInfo": null
//		}
		
		$orderId = $request->out_trade_no;
		$customInfo = $request->customInfo;
		
		$paramArray = explode("_", $customInfo);
		$aaReferrerId = $paramArray[0];
		$adId = $paramArray[1];

		$adInfo = DB::table('activity_definition')->where('adId', $adId)->first();
		
		$applyInfo = DB::table('activity_apply')->where('aaOrderId', $orderId)->first();
		if ($applyInfo->aaStats == 1){
			return $this->returnMsg(0, '重复回调');
		}
		DB::table('activity_apply')
			->where('aaId', $applyInfo->aaId)
			->update([
				'aaStats' => 1,
				'aaReferrerId' => $aaReferrerId,
			]);
		
		if ($aaReferrerId){
			$referrerApplyInfo = DB::table('activity_apply')
									->where('adId', $adId)
									->where('uId', $aaReferrerId)
									->where('aaStats', 1)
									->first();
		}else{
			$referrerInfo = DB::table('member_users')->where('muCode', $aaReferrerId)->first();
			if (!empty($referrerInfo)){
				if ($referrerInfo->muMemo == 'shareSeed'){
					$referrerInfo = 1;
				}
			}
			$referrerApplyInfo = null;
		}
		
		if ($aaReferrerId && !empty($referrerApplyInfo)){

			$boundResult = $this->common->boundRelation($applyInfo->acId, $applyInfo->uId, $aaReferrerId, 'share');
			Log::info('boundResult:');
			Log::info($boundResult);
			
			// 执行分销
			$host = config('admin.dataApiHost');
			$disUrl = $host."/distributionUsers/distribution";
			$disData = array();
			$disData['dcKey'] = $applyInfo->acId;
//			$disData['uId'] = $applyInfo->uId;
			$disData['uId'] = $aaReferrerId;
			$disData['money'] = $applyInfo->aaPrice;
			$disData['dpId'] = $adInfo->dpId;
			$disData['orderId'] = $orderId;
			$disData['operationUser'] = 'system';
			$disData['moneyCount'] = 0;
			$disData['saleNum'] = 1;
			$disData['dbMemo'] = 'activity_'. $applyInfo->adId;
			$disData['goodsId'] = $applyInfo->adId;
			$disData['goodsName'] = 'activity';
			$disData['customerUid'] = $applyInfo->uId;
			
			Log::info('disUrl:'.$disUrl);
			$disResult = Curl::to($disUrl)->withData($disData)->post();
			Log::info('disResult:');
			Log::info($disResult);
			
//			{
//				"code": 1,
//				"msg": "OK",
//				"data": {
//					"dcId": 7,
//					"orderId": "2019072901174714536",
//					"dpId": "3",
//					"dbSaleMoney": "0.01",
//					"createUser": "system",
//					"dbMemo": "activity_1",
//					"uId": "438cf62c490a833ee68e1a62cd883e8e",
//					"duParentUid": null,
//					"duGrandUid": null,
//					"dbSelfMoney": 8.8,
//					"dbParentMoney": 0,
//					"dbGrandMoney": 0,
//					"dbSurplusMoney": -8.790000000000001,
//					"dbSaleNum": "1"
//				}
//			}
			
			$disResult = json_decode($disResult ,true);
			$disResult = $disResult['data'];

			if ($disResult['dbSelfMoney'] > 0){
				DB::table('activity_apply')
					->where('adId', $applyInfo->adId)
					->where('uId', $aaReferrerId)
					->increment('aaShareMoney', $disResult['dbSelfMoney']);
					
				$userInfo = DB::table('member_users')->where('muCode', $disResult['uId'])->first();
				// 支付
				$companyPayUrl = $this->WX_HOST."/api/pay/companyPay";
				$companyPayData = array();
				$companyPayData['pcKey'] = $this->KEY;
				$companyPayData['clientIp'] = $request->getClientIp();
				$companyPayData['pay'] = $disResult['dbSelfMoney'];
				$companyPayData['desc'] = '奖励红包';
				$companyPayData['openid'] = $userInfo->openid;
				$companyPayData['uChannelId'] = $this->CHANNEL_ID;
				$companyPayData['cardName'] = '';
				$companyPayData['realName'] = 0;
				
				$companyPayResult = Curl::to($companyPayUrl)->withData($companyPayData)->post();
				Log::info('companyPayResult:');
				Log::info($companyPayResult);
			}
			if($disResult['dbParentMoney'] > 0){
				DB::table('activity_apply')
					->where('adId', $applyInfo->adId)
					->where('uId', $disResult['duParentUid'])
					->increment('aaShareMoney', $disResult['dbParentMoney']);
					
				$userInfo = DB::table('member_users')->where('muCode', $disResult['duParentUid'])->first();
				// 支付
				$companyPayUrl = $this->WX_HOST."/api/pay/companyPay";
				$companyPayData = array();
				$companyPayData['pcKey'] = $this->KEY;
				$companyPayData['clientIp'] = $request->getClientIp();;
				$companyPayData['pay'] = $disResult['dbParentMoney'];
				$companyPayData['desc'] = '奖励红包';
				$companyPayData['openid'] = $userInfo->openid;
				$companyPayData['uChannelId'] = $this->CHANNEL_ID;
				$companyPayData['cardName'] = '';
				$companyPayData['realName'] = 0;
				
				$companyPayResult = Curl::to($companyPayUrl)->withData($companyPayData)->post();
				Log::info('companyPayResult:');
				Log::info($companyPayResult);
			}
		}
		
		// 添加报名数
		DB::table('activity_definition')->where('adId', $applyInfo->adId)->increment('adApplyNum');
		 
//{
//  "code": 1,
//  "msg": "OK",
//  "data": {
//      "orderId": "aabbcc",
//      "dpId": "1",
//      "dbSaleMoney": "100",
//      "createUser": "Mark",
//      "dbMemo": "aabbcc",
//      "dbSelfMoney": "10.00",
//      "duParentId": 10,
//      "dbParentMoney": "5.00",
//      "dbGrandMoney": 0,
//      "dbSurplusMoney": 85,
//      "duParentUid": null,
//      "duGrandUid": null
//  }
//}
		return $this->returnMsg(1, 'OK');
	}
	
	public function addShareLog($acId, $adId, $asvViewUid, $asvShareUid){
		
		$vInfo = DB::table('activity_share_view')
					->where('acId', $acId)
					->where('adId', $adId)
					->where('asvViewUid', $asvViewUid)
					->where('asvShareUid', $asvShareUid)
					->first();
		if (empty($vInfo)){
			DB::table('activity_share_view')->insert([
				'acId' => $acId,
				'adId' => $adId,
				'asvViewUid' => $asvViewUid,
				'asvShareUid' => $asvShareUid
			]);
			return true;
		}
		return false;
	}
	
	/**
     * 通过code换取网页授权access_token
     *
     * @return mixed
     */
    private function getInfo($code)
    {
    	if (Cache::has($code)){
    		$info = Cache::get($code);
    		return $info;
    	}
    	
    	// 巴普营销
    	$appId = 'wxb8f879f3ecc43dc5';
        $secret = 'aab68259b13c6dffd031870ec623108e';

        $data = Curl::to('https://api.weixin.qq.com/sns/oauth2/access_token')
            ->withData(['appid' => $appId, 'secret'=> $secret, 'code' => $code, 'grant_type' => 'authorization_code'])
            ->get();

//		{ "access_token":"ACCESS_TOKEN",
//		"expires_in":7200,
//		"refresh_token":"REFRESH_TOKEN",
//		"openid":"OPENID",
//		"scope":"SCOPE" }
//		print_r($data);exit;
        $data = json_decode($data, true);
		if (!isset($data['access_token'])){
			return false;
		}
		
		$userInfoData = Curl::to('https://api.weixin.qq.com/sns/userinfo')
            ->withData(['access_token' => $data['access_token'], 'openid'=> $data['openid'], 'lang' => 'zh_CN'])
            ->get();
        $userInfoData = json_decode($userInfoData, true);
        Cache::put($code, $userInfoData, 10);
        return $userInfoData;

//      //重新设置缓存，有效期120分钟
//      Cache::put('access_token', $curl['access_token'], 120);

//      return $data;
    }
    
    public function boundPhone(Request $request){
    	
    	$sId = $request->input('sId');
		$adId = $request->input('adId');
		$code = $request->input('code', false);
		$custom = $request->input('custom');
		$mobile = $request->mobile;
		$openid = $request->openid;
		
		
		if (!$mobile){
			if (!$code){
				$host = $this->WX_HOST."/auth/wxHtmAuth";
				$thisUrl = urlencode(route('boundPhone'));
				$authUrl = $host."?redirect_uri={$thisUrl}&scope=snsapi_userinfo&custom=".$adId.'_'.$sId."&appid=".$this->appid;
				return redirect($authUrl);
			}
	
			$wxHtmlAuthorizeInfo = $this->getInfo($code);
			Cache::put($wxHtmlAuthorizeInfo['openid'], $wxHtmlAuthorizeInfo, 60);
			$paramArray = explode("_", $custom);
			$adId = $paramArray[0];
			$sId = $paramArray[1];
			
			return view("activity/bound", array('openid' => $wxHtmlAuthorizeInfo['openid'], 'sId' => $sId, 'adId' => $adId));
		}else{
			$sId = $request->sId;
			$adId = $request->adId;
			$info = Cache::get($openid);
			
			$muInfo = DB::Table('member_users')
						->where('mcId', $sId)
						->where('muMemo', 'import_activity_2')
						->where('muMobile', $mobile)
						->first();
			if (empty($muInfo)){
				return '绑定失败，无此电话号码！';
			}
			
			DB::Table('member_users')
				->where('mcId', $sId)
				->where('muMemo', 'import_activity_2')
				->where('muMobile', $mobile)
				->update(['openid'=>$info['openid'], 'muHeadUrl'=>$info['headimgurl'], 'muSex'=>$info['sex']]);
			return '绑定成功';
		}
    }
    
    public function registerShareSeed(Request $request){
    	
    	$sId = $request->input('sId');
		$adId = $request->input('adId');
		$code = $request->input('code', false);
		$custom = $request->input('custom');
		$muCode = $request->muCode;
		
		
		if (!$muCode){
			if (!$code){
				$host = $this->WX_HOST."/auth/wxHtmAuth";
				$thisUrl = urlencode(route('registerShareSeed'));
				$authUrl = $host."?redirect_uri={$thisUrl}&scope=snsapi_userinfo&custom=".$adId.'_'.$sId."&appid=".$this->appid;
				return redirect($authUrl);
			}
	
			$wxHtmlAuthorizeInfo = $this->getInfo($code);
			Cache::put($wxHtmlAuthorizeInfo['openid'], $wxHtmlAuthorizeInfo, 60);
			$paramArray = explode("_", $custom);
			$adId = $paramArray[0];
			$sId = $paramArray[1];
			
			$muInfo = $this->registerOrSign($sId, $wxHtmlAuthorizeInfo);
			$isShareSeed = false;
			if(isset($muInfo['muReferrerName'])){
				if ($muInfo['muReferrerName'] == 'shareSeed'){
					$isShareSeed = true;
				}
			}
			if ($isShareSeed){
				$thisUrl = route('activityView')."?sId=".$sId."&adId=".$adId;
				$shareUrl = $thisUrl."&referrerCode=".$muInfo['muCode'];
				return view("activity/qrcode", array('shareUrl' => $shareUrl, 'sId' => $sId, 'adId' => $adId));
			}else{
				return view("activity/qrcode", array('shareUrl' => false, 'sId' => $sId, 'adId' => $adId));
			}
		}else{
			$sId = $request->sId;
			$adId = $request->adId;
			
			$muInfo = DB::Table('member_users')
						->where('muCode', $muCode)
						->first();
			if (empty($muInfo)){
				return '绑定失败，系统错误！';
			}
			
			DB::Table('member_users')
				->where('muCode', $sId)
				->update(['muReferrerName'=> 'shareSeed']);
			
			$thisUrl = route('activityView')."?sId=".$sId."&adId=".$adId;
			$shareUrl = $thisUrl."&referrerCode=".$muInfo['muCode'];
			return view("activity/qrcode", array('shareUrl' => $shareUrl, 'sId' => $sId, 'adId' => $adId));
		}
    }
}
